package com.loong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.loong.dto.ClazzDTO;
import com.loong.entity.Clazz;
import com.loong.entity.Student;
import com.loong.mapper.ClazzMapper;
import com.loong.mapper.StudentMapper;
import com.loong.result.PageBean;
import com.loong.service.ClazzService;
import com.loong.vo.ClazzVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageBean list(ClazzDTO clazzDTO) {
        PageHelper.startPage(clazzDTO.getPage(), clazzDTO.getPageSize());
        List<ClazzVO> clazzList = clazzMapper.list(clazzDTO.getName(), clazzDTO.getBegin(), clazzDTO.getEnd());
        Page<ClazzVO> clazzPage = (Page<ClazzVO>) clazzList;
        return new PageBean(clazzPage.getTotal(), clazzPage.getResult());
    }

    @Override
    public List<Clazz> listAll() {
        return clazzMapper.selectList(null);
    }

    @Override
    public Clazz get(Integer id) {
        return clazzMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.eq("clazz_id", id);
        studentMapper.delete(qw);
        clazzMapper.deleteById(id);
    }

    @Override
    public void insert(Clazz clazz) {
        clazzMapper.insert(clazz);
    }

    @Override
    public void update(Clazz clazz) {
        clazzMapper.updateById(clazz);
    }
}
